import numpy as np

def read_txt_by_given_point_num(file_path: str, total_points: int = 5000):
    # 读取txt文件
    with open(file_path, 'r') as f:
        lines = f.readlines()

    # 找到"% Coordinates"所在的行号
    for i, line in enumerate(lines):
        if line.strip() == "% Coordinates":
            coordinates_start_index = i + 1
            break

    # 找到"% Elements (tetrahedra)"所在的行号
    for i, line in enumerate(lines):
        if line.strip() == "% Elements (tetrahedra)":
            elements_start_index = i + 1
            break

    # 提取"% Coordinates"和"% Elements (tetrahedra)"之间的数据
    coordinates = []
    for line in lines[coordinates_start_index:elements_start_index-1]:
        if line.strip() == "":
            break
        coordinates.append(list(map(float, line.strip().split())))
    coordinates = np.array(coordinates)

    # 提取"% Elements (tetrahedra)"之后的数据
    connection = []
    for line in lines[elements_start_index:]:
        if line.strip() == "":
            break
        connection.append(list(map(int, line.strip().split())))
    connection = np.array(connection)-1

    # 获取四面体的总数
    num_tetrahedras = len(connection)
    random_array = np.random.randint(
        low=0, high=num_tetrahedras, size=total_points)

    # 存储所有点坐标的集合
    vertices = np.array([])
    for index in random_array:
        v = connection[index]
        p = generate_random_point_in_tetrahedron(coordinates[v[0]],
                                                 coordinates[v[1]],
                                                 coordinates[v[2]],
                                                 coordinates[v[3]])
        vertices = np.append(vertices, p)

    # 将一维数组转换为二维数组
    vertices = vertices.reshape(-1, 3)
    # 将数组元素类型转换为 float32
    vertices = vertices.astype(np.float32)
    # 返回NumPy数组
    return vertices


# 在四面体内随机生成点
def generate_random_point_in_tetrahedron(v0, v1, v2, v3):
    while True:
        u1,u2,u3=np.random.random(3)
        if u1+u2> 1:
            continue
        if u1+u3> 1:
            continue
        if u2+u3> 1:
            continue
        if u1+u2+u3 > 1:
            continue
        break
    # 计算新点的坐标
    p = v0+ u1*(v1-v0) + u2*(v2-v0) + u3*(v3-v0)
    return p
